﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MetaDrive.Core
{    
    public class ProjectItemIterator : IEnumerable<EnvDTE.ProjectItem>
    {
        EnvDTE.Solution solution;
        EnvDTE.Project project;

        public ProjectItemIterator(EnvDTE.Solution solution)
        {
            if (solution == null)
                throw new ArgumentNullException("solution");

            this.solution = solution;
        }

        public ProjectItemIterator(EnvDTE.Project project)
        {
            if (project == null)
                throw new ArgumentNullException("project");

            this.project = project;
        }

        public static IEnumerable<EnvDTE.ProjectItem> Create(EnvDTE.Solution solution)
        {
            return new ProjectItemIterator(solution);
        }

        public static IEnumerable<EnvDTE.ProjectItem> Create(EnvDTE.Project project)
        {
            return new ProjectItemIterator(project);
        }

        public IEnumerator<EnvDTE.ProjectItem> GetEnumerator()
        {
            if (solution != null)
            {
                foreach (EnvDTE.Project currentProject in solution.Projects)
                    foreach (var currentProjectItem in Enumerate(currentProject.ProjectItems))
                        yield return currentProjectItem;
            }
            else
            {
                foreach (var currentProjectItem in Enumerate(project.ProjectItems))
                    yield return currentProjectItem;
            }
        }

        IEnumerable<EnvDTE.ProjectItem> Enumerate(EnvDTE.ProjectItems projectItems)
        {
            foreach (EnvDTE.ProjectItem item in projectItems)
            {
                yield return item;

                if (item.SubProject != null)
                {
                    foreach (EnvDTE.ProjectItem childItem in Enumerate(item.SubProject.ProjectItems))
                        yield return childItem;
                }
                else
                {
                    foreach (EnvDTE.ProjectItem childItem in Enumerate(item.ProjectItems))
                        yield return childItem;
                }
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
